interface TaskItem {
  isRunning: boolean
  queue: (() => unknown)[]
}
interface TaskSyncActuatorCollect {
  [key: string]: TaskItem
}
export default class TaskSyncActuator {
  private static syncQueues: TaskSyncActuatorCollect = {
    // key = {isRunning: boolean,queue: (()=>void)[]}
  }
  public static addSyncQueue(key: number | string = 'default', fun: () => unknown) {
    if (fun == null) return
    let currentValue: TaskItem = TaskSyncActuator.syncQueues[key]
    if (currentValue == null)
      TaskSyncActuator.syncQueues[key] = currentValue = {
        isRunning: false,
        queue: []
      } as TaskItem
    currentValue.queue.push(fun)
    TaskSyncActuator.run(currentValue)
  }

  private static async run(value: TaskItem) {
    if (value.isRunning) return
    value.isRunning = true
    const currentRunQueue = value.queue
    let task: (() => any) | undefined = undefined
    while ((task = currentRunQueue.shift()) != undefined) {
      const result = task!()
      if (result instanceof Promise) await result
    }
    value.isRunning = false
  }
}
